package com.cpic.blood.core.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPReply;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class FtpFileUtil {

    @Value("${ftp.host}")
    public static String ftpHost;

    @Value("${ftp.port}")
    public static String ftpPort;

    @Value("${ftp.username}")
    public static String ftpUserName;

    @Value("${ftp.password}")
    public static String ftpPassWord;

    /**
     * ftp 连接测试
     * @param host
     * @param port
     * @param userName
     * @param password
     * @return
     */
    public static boolean connectTest(String host,Integer port,String userName,String password) {
        boolean connectFlag=false;
        int reply;
        FTPClient ftpClient = new FTPClient();
        try {
            ftpClient.connect(host,port);
            //下面三行代码必须要，而且不能改变编码格式
            ftpClient.setControlEncoding("UTF-8");
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_NT);
            conf.setServerLanguageCode("zh");
            ftpClient.login(userName,password);
            reply = ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                log.info("connectToServer FTP server refused connection.");
                connectFlag=false;
            }else {
                connectFlag=true;
            }
        } catch (Exception e) {
            log.error("ftp " + ftpHost + " connect error", e);
        }finally {
            try {
                ftpClient.disconnect();
            } catch (Exception e) {
                log.error(e.getMessage(),e);
            }
        }
        return connectFlag;
    }

    public static void main(String[] args) {
        FtpFileUtil.connectTest(ftpHost,Integer.valueOf(ftpPort),ftpUserName,ftpPassWord);
    }
}
